

package GUI;

import CLIENT.Client;
import CLIENT.Message;
import FILE_SENDING.*;
import FILE_SENDING.RecieveFile;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.BevelBorder;

/**
 * This Is the mainPanel of a private chat conversation
* @author Talk2Me Team
 */
public class PrivateChatPanel extends JPanel implements MouseListener,ActionListener,KeyListener
{
    //***********Initialize Arguments****************//
    JTextArea _textArea;
    JTextArea _messageField;
    EmoticonsPanel _Emoticons;
    JButton _send;
    JButton _RecieveFile;
     JButton  _sendFile;
    Font _font;
    Color _TA_Color;
     Image _image3DP;
    Image _wall;
    String _histoy;
    String _chatwith;
    Client _client;
    ObjectOutputStream out = null;

    Image _image3DP_run;

    //File managers
    SendFile _sendFileManager = null;
    RecieveFile _recieveFileManager=null;
    boolean _IsSending=false;//Declares Whether This user is in recieve or send file mode

    //**********************************************//
    
    /**
     * constructor for PrivateChatPanel
     */
    public PrivateChatPanel(Client client, ObjectOutputStream o, String s)
    {
        //setting the Layout Manager
        setLayout(null);

        //set the image
         _image3DP_run = Toolkit.getDefaultToolkit().getImage("Pics/3D Postman running copy.gif");
        _client = client;
        //out = (ObjectOutputStream)_client.GetOut();
        out = o;
        _chatwith = s;

        //Set the Image
             _wall = Toolkit.getDefaultToolkit().getImage("Pics/Wall.jpg");
            _image3DP=Toolkit.getDefaultToolkit().getImage("3D Postman No BG.gif");
        //Create Colors
            _TA_Color=new Color(255,255,255);//create TextArea color
            

             //Initialize Font
            _font=new Font("Arial",Font.BOLD,13);

        //Initialize TextArea
                _textArea = new JTextArea();
                _textArea.setFont(_font);
                _textArea.setBackground(_TA_Color);
                _textArea.setEditable(false);
                  JScrollPane text_Scroll=new JScrollPane(_textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
               text_Scroll.setBounds(100, 50, 630, 350);
                this.add(text_Scroll);
        //initialize message field
            _messageField=new JTextArea("Enter your message here ...");
            _messageField.setFont(_font);
            _messageField.setToolTipText("Enter Your Message Here ...");
            _messageField.setColumns(50);
            _messageField.addKeyListener(this);
            JScrollPane mess_Scroll=new JScrollPane(_messageField, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            mess_Scroll.setBounds(100, 430, 350, 60);
            _messageField.setBorder(new BevelBorder(BevelBorder.LOWERED));
            this.add(mess_Scroll);
        //initialize EmoticonsPanel(Panel)
            _Emoticons=new EmoticonsPanel();
           // _Emoticons.setBounds(100, 390,330,40);
             _Emoticons.setBounds(100, 400, 350, 30);
           for(int i=0;i<_Emoticons._size;i++)
                _Emoticons._Buttons[i].addMouseListener(this);
            this.add(_Emoticons);
        //initialize "send" button
            _send=new JButton("SEND");
             _send.setBounds(450, 430, 165, 60);
           _send.addMouseListener(this);
           _send.setBorder(new BevelBorder(BevelBorder.RAISED));
            _send.addActionListener(this);

            this.add(_send);
       _sendFile=new JButton("Send File");
            _sendFile.setBounds(615, 430,165,60);
            _sendFile.addMouseListener(this);
            _sendFile.addActionListener(this);
            _sendFile.setBorder(new BevelBorder(BevelBorder.RAISED));
            this.add(_sendFile);

             //initialize "_recieve file" button
            _RecieveFile=new JButton("Recieve File");
            _RecieveFile.setBounds(615, 490, 165, 60);
            _RecieveFile.addMouseListener(this);
            _RecieveFile.addActionListener(this);
            this.add(_RecieveFile);

//               //initialize "history" button
//            _history=new JButton("History");
//            _history.setBounds(225, 400,125 , 30);
//            _history.addMouseListener(this);
//            _history.addActionListener(this);
//            this.add(_history);
//
//               //initialize "music" button
//            _music=new JButton("Music");
//            _music.setBounds(350, 400, 125, 30);
//            _music.addMouseListener(this);
//            _music.addActionListener(this);
//            this.add(_music);
//
//
//
//               //initialize "invite" button
//            _invite=new JButton("Invite Friends");
//              _invite.setBounds(475, 400, 255, 30);
//          _invite.addMouseListener(this);
//            _invite.addActionListener(this);
//            this.add(_invite);



        
    }
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        _font=new Font("Guttman",Font.BOLD,30);
        g.setFont(_font);
         //draw the images
         g.drawImage(_wall, 0, 0, null);
         g.drawImage(_image3DP_run, 580 , 400, null);
         g.drawString(this.getToolTipText(),100, 30);


        //paint the color of the panel and he's components by the colors
            _textArea.setBackground(_TA_Color);
            _messageField.setBackground(_TA_Color);



    }
/**
 * this function changes the "theme" of the panel by changing the BackGroung color and the TextArea color
 * @param BG the new Background color
 * @param TA the new TextArea color
 */
    public void ChangeTheme(Color BG,Color TA)
    {
        _TA_Color=TA;
        repaint();
    }
    /**
     * This Methos handle events on Emoticons Panel
     * @param e
     */
    public void mouseClicked(MouseEvent e) // handle events on emoticons buttons
    {
        String s=_messageField.getText();
        _messageField.setText(null);

        //EmoticonsPanel events
                if(e.getSource()==_Emoticons._Buttons[0])//happy
                {
                    _messageField.insert(s+":-)",0);
                }
                if(e.getSource()==_Emoticons._Buttons[1])//sad
                {
                    _messageField.insert(s+":-(",0);
                }
                if(e.getSource()==_Emoticons._Buttons[2])//wink
                {
                    _messageField.insert(s+";-)",0);
                }
                if(e.getSource()==_Emoticons._Buttons[3])//angry
                {
                    _messageField.insert(s+">:(",0);
                }
                     if(e.getSource()==_Emoticons._Buttons[4])//XD
                {
                    _messageField.insert(s+":XD",0);
                }
             if(e.getSource()==_Emoticons._Buttons[5])//confused
                {
                    _messageField.insert(s+":s",0);
                }
        if(e.getSource()==_Emoticons._Buttons[6])//frown
                {
                    _messageField.insert(s+":- -(",0);
                }
        if(e.getSource()==_Emoticons._Buttons[7])//lol
                {
                    _messageField.insert(s+"^^)",0);
                }
        if(e.getSource()==_Emoticons._Buttons[8])//biggrin
                {
                    _messageField.insert(s+":-|",0);
                }
        if(e.getSource()==_Emoticons._Buttons[9])//neutral
                {
                    _messageField.insert(s+":|",0);
                }
        if(e.getSource()==_Emoticons._Buttons[10])//oh
                {
                    _messageField.insert(s+":-O",0);
                }
        if(e.getSource()==_Emoticons._Buttons[11])//teeth
                {
                    _messageField.insert(s+":-D",0);
                }
        if(e.getSource()==_Emoticons._Buttons[12])//winktongue
                {
                    _messageField.insert(s+":P",0);
                }

    }
    public void actionPerformed(ActionEvent e)
    {
        //"send" pressed
                if(e.getSource()==_send)
                {
                            try
                            {
                                String s = _messageField.getText();
                                _messageField.setText(null);
                                Calendar cal = Calendar.getInstance();
                                String time = "(" + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND) + ")";
                                String all=_textArea.getText();
                                _textArea.setText(all+_client.GetName() + time + " :\n\t" + s + "\n");
                //                _textArea.insert("You Said " + time + " :\n\t" + s + "\n", _textArea.getSelectionEnd());
                                SendMessage(s);
                            }
                            catch (IOException ex)
                            {
                                Logger.getLogger(PrivateChatPanel.class.getName()).log(Level.SEVERE, null, ex);
                            }
                }
                if(e.getSource()==_sendFile)
                {
                   _sendFileManager = new SendFile(this);
                   Thread t = new Thread(_sendFileManager);
                   t.run();
                   //_sendFileManager.run();
                   _IsSending = true;
                }
                if(e.getSource()==_RecieveFile)
                {
            try {
                _recieveFileManager = new RecieveFile(this);

            } catch (UnknownHostException ex) {
                Logger.getLogger(PrivateChatPanel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(PrivateChatPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
//                        try
//                        {
////                            _recieveFileManager = new RecieveFile(this);
//                        }
//                        catch(IOException ex2)
//                        {
//                        }

                }

    }
        /**
         * This method sends a message to the person we talk in the private chat
         * @param msg - the string message we want to send
         * @throws IOException
         */
       public void SendMessage(String msg) throws IOException
        {
           System.out.println("The client is sending this: " + msg);

		if ( _client.GetSocket() != null && out == null)
		{
                    out = new ObjectOutputStream(_client.GetSocket().getOutputStream());
		}
           Message m = new Message(msg,_client.GetName());
           m.SetClientsrc(_client.GetName());
           m.SetClientdst(_chatwith);

		if ( out != null )
                {
                    out.writeObject(m);   // send msg to the server
                    out.flush();
                }
        }
        /**
         *  This method recieves a message from the Connection and display it on the screen
         * it handles also system messages
         * @param msg - The Message we recieve
         * @throws IOException
         * @throws UnknownHostException
         * @throws InterruptedException
         */
        public void RecieveMessage(Message msg) throws IOException, UnknownHostException, InterruptedException
        {
            if(msg.GetString().startsWith("Give Me Your IP"))//The Send File Wants to Open A socket For file transferring
            {
                SendMessage("My IP is "+InetAddress.getLocalHost().getHostAddress()+"");
                return;
            }
            if(msg.GetString().startsWith("My IP is"))//You recieved an answer for "Give Me Your IP"
            {
                   String s = msg.GetString().replaceAll("My IP is ","");//remove The beginning and get only the IP
                   while( _recieveFileManager==null)
                   {
                       //wait for the thread of the reciever to be ready ...
                   }
                    _recieveFileManager.UpdateIP(s);
                    Thread t = new Thread(_recieveFileManager);
                   t.run();
                   return;
            }
             Calendar cal=Calendar.getInstance();
             String time="("+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+")";
             String all=_textArea.getText();
             _textArea.setText(all+msg.GetClientsrc()+" send "+time+" :\n\t"+msg.GetString()+"\n");
             Toolkit.getDefaultToolkit().beep();

        }
    public void RecieveControlMessage(String msg)
    {
        String all=_textArea.getText();
        _textArea.setText(all+msg+"\n");
    }
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void keyPressed(KeyEvent e) {
    }
    public void keyReleased(KeyEvent e) {
    }
    public void keyTyped(KeyEvent e) {
    }
    public void SetISSending(boolean b){_IsSending=b;}
}

   

